package com.example.word.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.example.dict.R;
import com.example.word.bean.Dict;
import com.example.word.bean.Word;
import com.example.word.util.FileUtils;
import com.example.word.util.HttpUtils;
import com.example.word.util.ImageCompressor;
import com.example.word.util.MessageUtils;
import com.example.word.util.Response;
import com.example.word.util.StringUtils;
import com.example.word.widget.ActionBar;

import org.litepal.crud.DataSupport;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 添加页面
 */
public class AddActivity extends AppCompatActivity {
    private ActionBar mTitleBar;//标题栏
    private Activity myActivity;
    private EditText etTitle;//标题
    private EditText etImg;//图片
    private Spinner spType;//类型
    private EditText etContent;//内容
    private EditText etWordNumber;//数量
    private Button btnSave;//保存
    private ImageView ivImg;//图片
    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private Dict currentDict;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myActivity = this;
        setContentView(R.layout.activity_add);
        etTitle = findViewById(R.id.title);
        spType = findViewById(R.id.dictType);
        etImg = findViewById(R.id.img);
        etContent = findViewById(R.id.content);
        etWordNumber = findViewById(R.id.wordNumber);
        ivImg = findViewById(R.id.iv_img);
        btnSave = findViewById(R.id.btn_save);
        mTitleBar = findViewById(R.id.myActionBar);
        //侧滑菜单
        mTitleBar.setData(myActivity, "编辑信息", R.drawable.ic_back, 0, 0, getResources().getColor(R.color.colorPrimary), new ActionBar.ActionBarClickListener() {
            @Override
            public void onLeftClick() {
                finish();
            }

            @Override
            public void onRightClick() {
            }
        });
        // 设置主题
        if (!com.example.word.ui.activity.MainActivity.colorChange) {
            mTitleBar.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
            btnSave.setBackground(getResources().getDrawable(R.drawable.btn_border_fill));
        } else {
            mTitleBar.setBackgroundColor(getResources().getColor(R.color.myColor));
            btnSave.setBackground(getResources().getDrawable(R.drawable.btn_border_fill_my_color));
        }
        initView();
    }

    private void initView() {
        //Activity之间通过Intent传递值
        currentDict = (Dict) getIntent().getSerializableExtra("dict");
        if (currentDict != null) {
            etTitle.setText(currentDict.getDict());
            etTitle.setEnabled(false);
            spType.setSelection(currentDict.getTypeId());
            etImg.setText(currentDict.getImg());
            etContent.setText(currentDict.getContent());
            etWordNumber.setText(String.valueOf(currentDict.getWordNumber()));
            spType.setSelection(currentDict.getTypeId(), true);
            Glide.with(myActivity)
                    .asBitmap()
                    .load(HttpUtils.downloadUrl + currentDict.getImg())
                    .error(R.drawable.ic_error)
                    .skipMemoryCache(true)
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .into(ivImg);
        } else {
            etTitle.setEnabled(true);
        }
        etImg.setEnabled(false);

        ivImg.setOnClickListener(v -> {
            if (ContextCompat.checkSelfPermission(myActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(myActivity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 789);
            } else {
                xzImage();
            }
        });
        etImg.setOnClickListener(v -> {
            if (ContextCompat.checkSelfPermission(myActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(myActivity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 789);
            } else {
                xzImage();
            }
        });
    }

    private void xzImage() {

        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, 123); // 打开本地存储
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case 123:
                if (data == null) {
                    return;
                }
                File file = ImageCompressor.compressImage(myActivity, data.getData(), 256);
                HttpUtils.uploadImage("/upload", file, myActivity, HashMap.class, new HttpUtils.ApiCallback<HashMap>() {
                    @Override
                    public void onSuccess(Response<HashMap> response) {
                        MessageUtils.show("上传成功", myActivity);
                        etImg.setText(response.getData().get("file").toString());
                        //显示图片
                        Glide.with(myActivity).asBitmap().load(data.getData()).error(R.drawable.ic_error).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE).into(ivImg);
                    }
                });
                break;
            default:
                break;
        }
    }

    public void save(View view) {
        String title = etTitle.getText().toString();
        String img = etImg.getText().toString();
        String content = etContent.getText().toString();
        Integer typeId = spType.getSelectedItemPosition();
        if ("".equals(title)) {//如果输入为空
            Toast.makeText(myActivity, "标题不能为空", Toast.LENGTH_LONG).show();
            return;
        }
//        if ("".equals(issuer)) {
//            Toast.makeText(myActivity, "价格不能为空", Toast.LENGTH_LONG).show();
//            return;
//        }
        if ("".equals(img)) {
            Toast.makeText(myActivity, "请上传图片", Toast.LENGTH_LONG).show();
            return;
        }
        if ("".equals(content)) {
            Toast.makeText(myActivity, "描述不能为空", Toast.LENGTH_LONG).show();
            return;
        }
        Map<String, String> requestParam = new HashMap<>();
        requestParam.put("dict", title);
        requestParam.put("content", content);
        requestParam.put("typeId", String.valueOf(typeId));
        requestParam.put("img", img);
        if (currentDict != null) {
            requestParam.put("isUpdate", "Y");
        }
        // 调用 API 客户端的方法
        HttpUtils.sendGetRequest("/saveDict", requestParam, myActivity, Object.class, response -> {
            MessageUtils.show("保存成功！", myActivity);
            setResult(RESULT_OK);
            finish();//关闭页面
        });
    }

    //选择权限后的回调函数
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 789:
                //检查是否有读取存储卡的权限，如果有则选择图片，如果没有则提示
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    xzImage();
                } else {
                    Toast.makeText(this, "You denied the permission", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }
    }
}
